//
//  model.cpp
//  Survival
//
//  Created by Maxime BACOUX on 10/08/12.
//
//

#include "model.h"
#include "windows-mac.h"
#include <sstream>

Model::Model(std::string nom)
{
	this->load(nom);
}

void Model::load(std::string nom)
{
	std::cout << "Importing object " + nom + "(.obj)\n";
	FILE* fichier = NULL;
	fichier = fopen((_RESPATH + nom + ".obj").c_str(), "r");
	if(fichier == NULL)
	{
		std::cout << "Erreur fichier !\n";
		return;
	}
	char carac;
	
	while((carac = getc(fichier)) != EOF)
	{
		int vertNb = vertices.size() + 1;
		if(carac == 'v')
		{
			vertex vert = {0,0,0};
			carac = getc(fichier);
			std::stringstream ss;
			
			do
			{
				carac = getc(fichier);
				if(carac != ' ')
				{
				ss << carac;
				}
			}
			while (carac != ' ' && carac != EOF);
			
			ss >> vert.x;
			
			ss.clear();
			ss.str(std::string());
			
			do
			{
				carac = getc(fichier);
				if(carac != ' ')
				{
					ss << carac;
				}
			}
			while (carac != ' ' && carac != EOF);
	
			ss >> vert.z;
			ss.clear();
			ss.str(std::string());
			
			do
			{
				carac = getc(fichier);
				if(carac != ' ' && carac != '\n')
				{
					ss << carac;
				}
			}
			while (carac != ' ' && carac != EOF && carac != '\n');
			ss >> vert.y;
			vertices.push_back(vert);
			
			std::cout << "Vertice " << vertNb << " imported : X=" << vert.x << ", Y=" << vert.y << ", Z=" << vert.z << ".\n";
			
		}
		else if(carac == 'f')
		{
			int facesNb = faces.size();
			
			std::vector<int> face;
			
			std::cout << "Importing face " << facesNb + 1 << "." << std::endl;
			
			getc(fichier);
			
			while (carac != '\n' && carac != EOF)
			{
				std::stringstream ss;
				do
				{
					carac = getc(fichier);
					if(carac != '\n' && carac != EOF && carac != ' ')
					{
						ss << carac;
					}
				}
				while (carac != '\n' && carac != EOF && carac != ' ');
				
				int tmp;
				ss >> tmp;
				face.push_back(tmp);
				
			}
			faces.push_back(face);
			
			
		}
		else
		{
			skipLine(fichier);
		}
	}
	
	std::cout << "Object " + nom + ".obj was imported.\n";
}

void Model::skipLine(FILE* file)
{
	int carac = 0;
	while (carac != '\n' && carac != EOF)
	{
		carac = getc(file);
	}
}

void Model::draw()
{
	for(int i = 0; i < faces.size(); i++)
	{
		glBegin(GL_POLYGON);
		glColor3ub(255,255,255);
		for(int j = 0; j < faces[i].size(); j++)
		{
			glVertex3d(vertices[faces[i][j]-1].x, vertices[faces[i][j]-1].z, vertices[faces[i][j]-1].y);
		}
		
		glEnd();
	}
}

Model::~Model()
{
	
}